package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 设置博客的附加信息
        records.forEach(blog -> {
            setBlogUserInfo(blog); // 设置发布该博客的用户信息
            setIsLiked(blog); // 设置当前用户是否点赞
        });
        return Result.ok(records);
    }


    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog == null) {
            return Result.fail("博文不存在");
        }
        setBlogUserInfo(blog);
        setIsLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        // 用户id
        String userId = UserHolder.getUser().getId().toString();
        // 用set集合保存点赞过该博文的用户id
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 1.查询redis，判断用户是否点过赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        if(score != null) {  // 1.1点过，取消点赞
            // 1.1.1表blog中的字段liked值减1
            boolean isSuccess = lambdaUpdate().setSql("liked = liked - 1").eq(Blog::getId, id).update();
            if(isSuccess) {
                // 1.1.2删除set集合中的用户id
                stringRedisTemplate.opsForZSet().remove(key, userId);
            }
        } else {   // 1.2未点过，点赞
            // 1.2.1表blog中的字段liked值加1
            boolean isSuccess = lambdaUpdate().setSql("liked = liked + 1").eq(Blog::getId, id).update();
            if(isSuccess) {
                // 1.2.2添加用户id到set集合，时间戳作为分数，实现先点赞的排在前面
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 查询点赞的用户id
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()) {
            return Result.ok();
        }
        // id类型转换，String->Long
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String userIdStr = StrUtil.join(",", userIds);
        // 查询用户信息
        List<User> users = userService
                .lambdaQuery()
                .in(User::getId, userIds)
                .last("order by field(id," + userIdStr + ")")
                .list();
        // 封装为UserDTO
        List<UserDTO> userDTOs = BeanUtil.copyToList(users, UserDTO.class);
        // 返回结果
        return Result.ok(userDTOs);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess) {
            return Result.fail("发布失败");
        }
        // 推送到所有粉丝
        // 查询当前用户的粉丝 select from tb_follow where follow_user_id = ?
        List<Follow> followList = followService.lambdaQuery().eq(Follow::getFollowUserId, user.getId()).list();
        // 遍历粉丝列表，将博文保存到redis的zset集合中(粉丝的feed流收件箱)
        if(followList != null && !followList.isEmpty()) {
            followList.forEach(follow -> {
                Long followUserId = follow.getUserId();  // 注意不要混乱了，这里是getUserId，获取到的是粉丝的id！
                // feed:userId = {}：表示userId这名用户关注的up的博文的id集合
                stringRedisTemplate.opsForZSet().add(
                        RedisConstants.FEED_KEY + followUserId,
                        blog.getId().toString(),
                        System.currentTimeMillis());
            });
        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        // 查询当前用户的博客收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 解析博客收件箱：拿到blogId、minTime和offset
        long minTime = 0;
        int nextOffset = 1;
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // blogId
            blogIds.add(Long.valueOf(tuple.getValue()));
            // minTime和offset，一个小算法
            long time = tuple.getScore().longValue();
            if(minTime == time) {
                nextOffset++;
            } else {
                minTime = time;
                nextOffset = 1;
            }
        }

        // 查询博文信息
        String blogIdsStr = StrUtil.join(",", blogIds);
        List<Blog> blogs = lambdaQuery()
                .in(Blog::getId, blogIds)
                .last("order by field(id, " + blogIdsStr +")")
                .list();
        // 设置博文的补充信息：用户信息、当前用户是否点赞
        blogs.forEach(blog -> {
            setBlogUserInfo(blog);
            setIsLiked(blog);
        });
        // 封装到ScrollResult中
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(nextOffset);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }


    /**
     * 设置发布该博文的用户信息
     * @param blog 博文信息
     */
    private void setBlogUserInfo(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


    /**
     * 设置博文的isLike字段
     * @param blog 博文信息
     */
    private void setIsLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            // 未登录，无需查询是否点赞
            return;
        }
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        String userId = UserHolder.getUser().getId().toString();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        blog.setIsLike(score != null);
    }
}
